package com.book.book.controller;

import com.book.book.constant.Constants;
import com.book.book.model.UserInfo;
import com.book.book.service.UserService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public boolean login(String name, String password, HttpSession session) {
        try {
            // 输入验证
            if (!StringUtils.hasLength(name) || !StringUtils.hasLength(password)) {
                logger.info("用户名或密码为空，登录失败");
                return false;
            }
            UserInfo userInfo=userService.getuser(name);
            if(userInfo==null)return false;
String VALID_USERNAME=name;
            String VALID_PASSWORD=userInfo.getPassword();
            // 验证用户名和密码
            if (VALID_USERNAME.equals(name) && VALID_PASSWORD.equals(password)) {
                session.setAttribute(Constants.SESSION_USER_KEY, userInfo);
                logger.info("用户 {} 登录成功", name);
                return true;
            }
            logger.info("用户名或密码错误，登录失败");
            return false;
        } catch (Exception e) {
            logger.error("登录过程中出现异常", e);
            return false;
        }
    }
}
